/*
 * @Author: fisher
 * @Date: 2024-02-20 17:28:03
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-11 09:42:43
 * @FilePath: \allfront\src\hooks\useAxios.js
 * @Description:
 */
import { ref } from 'vue';
import axios from 'axios';
import router from '@/router/index.js';
const proxy = import.meta.env.VITE_APP_PROXY;
export function useAxios(baseURL) {
  const res = ref(null);
  const error = ref(null);
  const loading = ref(false);
  // 创建 axios 实例
  const instance = axios.create({
    baseURL: baseURL || proxy, // 可以根据需要传入基础 URL
    timeout: 20000, // 请求超时时间
  });
  // 设置请求拦截器
  instance.interceptors.request.use(
    config => {
      loading.value = true;
      // 添加其他请求前的处理逻辑，比如 token
      const token = localStorage.getItem('jwtToken');
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
      }
      return config;
    },
    err => {
      loading.value = false;
      error.value = err;
      return Promise.reject(err);
    },
  );
  // 设置响应拦截器
  instance.interceptors.response.use(
    response => {
      loading.value = false;
      // console.log('response', response);
      // 在分片上传时不显示提示成功！循环次数 太多了。
      if (
        response.config.url != '/upload/bigFile' &&
        !response.config.url.includes('/upload/getMergeProgress/') &&
        !response.config.url.includes('/ueserver/getUnzipUeProgress/')
      ) {
        ElMessage({
          message: response.data.message,
          type: 'success',
        });
      }
      return response;
    },
    err => {
      loading.value = false;
      error.value = err;
      ElMessage({
        message: err.response.data.message,
        type: 'error',
      });

      if (err.response.status == 401) {
        router.push({
          path: '/',
        });
      }
      return Promise.reject(err);
    },
  );
  // 定义 get 方法
  const get = async (url, params = {}, headers = {}) => {
    try {
      const response = await instance.get(url, { params }, { headers });
      res.value = response.data;
      return response.data;
    } catch (err) {
      error.value = err;
    }
  };
  // 定义 post 方法
  const post = async (url, payload = {}, headers = {}) => {
    try {
      const response = await instance.post(url, payload, { headers });
      res.value = response.data;
      return response.data;
    } catch (err) {
      error.value = err;
    }
  };
  return { res, loading, error, get, post };
}
